package com.jacken.mars.utils;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

;

@Component
public class HttpUtils {


    public static String doPost(String URL){
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = null;
        try{
            URL url = new URL(URL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            //发送POST请求必须设置为true
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(10000);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("x-csrf-token", "52b67428-c0f2-4145-8112-7c46867b6e73");
            conn.setRequestProperty("cookie", "cna=Y+TkFs6ublQCAXZwSO4Lc1Bj; aliyun_choice=CN; iaGreyFlag=1585189243154; _ga=GA1.2.2101463277.1586761167; aliyun_lang=zh; console_base_assets_version=3.20.3; _bl_uid=52kmpje0j51n65ywXqp4pnCimgke; aliyunAliothSource=eyJzcG0iOiI1MTc2LjEyOTAxMDE1LjFlbTJ3aXJzYi5kNzEiLCJzY20iOiIyMDE0MDcyMi4yOTc5LjEuMjg1OSJ9; ping_test=true; t=842c218c82c201387be46ffab3e27e35; _tb_token_=eae04688038e7; cookie2=1155e3939812b01d663aff92f7e3197b; _samesite_flag_=true; UC-XSRF-TOKEN=52b67428-c0f2-4145-8112-7c46867b6e73; channel=eu1m37E4lMPQWWKX0dkn8kYPR37u0Ua9hHnXjMxU3Zc%3D; _hvn_login=6; currentRegionId=cn-hangzhou; activeRegionId=cn-hangzhou; xlly_s=1; login_aliyunid_pk=1905058489823422; UM_distinctid=176e02d59348d2-07865e11a12d4a-c791039-1fa400-176e02d5935c87; csg=20271140; login_aliyunid=\"scdx****\"; login_aliyunid_ticket=euf0vpmV*s*CT58JlM_1t$w33Z$hNSeFtzSX5UtHtCmvKUsibHqc3jetbHd4PYz2LF_Mcpof_BNTwUhTOoNC1ZBeeMfKJzxdnb95hYssNIZor6q7SCxRtgmGCbifG2Cd4ZWazmBdHI6sgXZqg4XFWQKy0; login_aliyunid_luid=\"BG+w0GBAvRyddbf519b11d795999b347b652658a36a+vYHAmyUbUzwkmrxzMrm5jg==\"; login_aliyunid_csrf=_csrf_tk_1465710090372615; login_aliyunid_abi=\"BG+PaD132h4866e77b0c4779618de9817eb9eb3d370+jIUzEahx8+b+793+ynN0GY6tgHeUY/N9Rnzd/Fwquphv+lfuvKA=\"; login_aliyunid_pks=\"BG+M2XWnMcyc82wvM1i72owcrukfLFnkZDWa0mjwOWUDPk=\"; hssid=1jPIs4EvLb7rQpZQa5jbvkA1; hsite=6; aliyun_country=CN; aliyun_site=CN; FECS-XSRF-TOKEN=98f60bc3-ff67-444f-adae-fed925d016a2; FECS-UMID=%7B%22token%22%3A%22Y09e1ae4190d360a5a2daaacf245be91a%22%2C%22timestamp%22%3A%2290674988585C5F4755406D75%22%7D; JSESSIONID=6589f239-c4fb-4436-8619-8d7307f8c8a1; CC-XSRF-TOKEN=1cfd97f6-bd41-4c89-92a8-3b44072e16fa; tfstk=cyE1BJ2hkCA1VR72bR6E3gqP343VZFJShNGgCPcvdEGekj21iitrNAEaoIKKyv1..; l=eBPQ6HF7OvoUJ87N4Ofwourza77OSIRAguPzaNbMiOCPOE1y5m-hBZ89-AL2C3GVhsdJR3uKcXmQBeYBqnbussQ-u1kmz4kmn; isg=BDU18ppZhgwkg-K-7T-GxWGURLHvsunE8nshErda8az7jlWAfwL5lEMI2FK4zgF8");
              //获取输出流
            out = new OutputStreamWriter(conn.getOutputStream());
            String jsonStr = "{\"qry_by\":\"name\", \"name\":\"Tim\"}";
            out.write(jsonStr);
            out.flush();
            out.close();
            //取得输入流，并使用Reader读取
            if (200 == conn.getResponseCode()){
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null){
                    result.append(line);
                }
            }else{
                System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(out != null){
                    out.close();
                }
                if(in != null){
                    in.close();
                }
            }catch (IOException ioe){
                ioe.printStackTrace();
            }
        }
        return result.toString();
    }


    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString;
            if (StringUtils.isEmpty(param)){
                 urlNameString=url;
            }else {
                urlNameString = url + "?" + param;
            }
            URL realUrl = new URL(urlNameString);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 25378));
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection(proxy);
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36");
            // 建立实际的连接
            connection.connect();
            String contentEncoding = connection.getContentEncoding();

            InputStream inputStream = connection.getInputStream();

            byte[] getData = readInputStream(inputStream);
            inputStream.read(getData);
            String str = new String(getData);
            System.out.println ("打印内容："+str);

        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    public static String uncompressString(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(str
                .getBytes("ISO-8859-1"));
        GZIPInputStream gunzip = new GZIPInputStream(in);
        byte[] buffer = new byte[256];
        int n;
        while ((n = gunzip.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }
        return out.toString();
    }




    public static String doGet(String URL){
        HttpURLConnection conn = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuilder result = new StringBuilder();
        try{
            //创建远程url连接对象
            URL url = new URL(URL);
            //通过远程url连接对象打开一个连接，强转成HTTPURLConnection类
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(15000);
            conn.setReadTimeout(60000);
            conn.setRequestProperty("Accept", "application/json");
            //发送请求
            conn.connect();
            //通过conn取得输入流，并使用Reader读取
            if (200 == conn.getResponseCode()){
                is = conn.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String line;
                while ((line = br.readLine()) != null){
                    result.append(line);
                    System.out.println(line);
                }
            }else{
                System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
            }
        }catch (MalformedURLException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(br != null){
                    br.close();
                }
                if(is != null){
                    is.close();
                }
            }catch (IOException ioe){
                ioe.printStackTrace();
            }
            conn.disconnect();
        }
        return result.toString();
    }
}
